package org.codehaus.activemq.transport.reliable;

import java.net.URI;
import java.net.URISyntaxException;
import javax.jms.JMSException;
import org.codehaus.activemq.message.WireFormat;
import org.codehaus.activemq.transport.TransportChannel;
import org.codehaus.activemq.transport.composite.CompositeTransportChannelFactory;
import org.codehaus.activemq.util.JMSExceptionHelper;

public class ReliableTransportChannelFactory extends CompositeTransportChannelFactory
{
  public TransportChannel create(WireFormat wireFormat, URI remoteLocation)
    throws JMSException
  {
    try
    {
      return new ReliableTransportChannel(wireFormat, parseURIs(remoteLocation));
    } catch (URISyntaxException e) {
    	   throw JMSExceptionHelper.newJMSException("Can't parse list of URIs for: " + remoteLocation + ". Reason: " + e, e);
    	   
    }
  }

  protected URI[] randomizeURIs(URI[] uris)
  {
    URI[] result = uris;
    if ((uris != null) && (uris.length > 1)) {
      result = new URI[uris.length];
      SMLCGRandom random = new SMLCGRandom();
      int startIndex = (int)(random.nextDouble() * (uris.length + 1));
      int count = 0;
      for (int i = startIndex; i < uris.length; i++) {
        result[(count++)] = uris[i];
      }
      for (int i = 0; i < startIndex; i++) {
        result[(count++)] = uris[i];
      }
    }
    return result;
  }
}